package me.hunche.app.service.impl;

import java.io.IOException;

import me.hunche.app.service.TemplateService;
import me.hunche.app.util.FreeMarkerUtility;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class TemplateServiceImpl implements TemplateService, InitializingBean {
	private static final Logger logger = Logger.getLogger(TemplateServiceImpl.class);

	private Configuration freemarkerCfg = null;
	private String templatePath = "/templates";

//	@Override
	public void afterPropertiesSet() throws Exception {
		freemarkerCfg = new Configuration();
		freemarkerCfg.setClassForTemplateLoading(FreeMarkerUtility.class, templatePath);
	}

//	@Override
	public String process(String templateName, Object rootMap) {
		String returnString = null;
		if (logger.isDebugEnabled()) {
			logger.debug("process(String, Object) - start");
		}
		try {
			Template template = freemarkerCfg.getTemplate(templateName);
			returnString = FreeMarkerTemplateUtils.processTemplateIntoString(template, rootMap);
			if (logger.isDebugEnabled()) {
				logger.debug("process(String, Object) - end");
			}
		} catch (TemplateException e) {
			logger.error("process(String, Object)", e);
		} catch (IOException e) {
			logger.error("process(String, Object)", e);
		}
		if (logger.isDebugEnabled()) {
			logger.debug("process(String, Object) - end");
		}
		return returnString;
	}

	public void setTemplatePath(String templatePath) {
		this.templatePath = templatePath;
	}
}
